import asyncio
import edge_tts

# 语音合成参数配置
VOICE = "zh-CN-XiaoxiaoNeural"  # 语音类型：中文小晓女声
RATE = '-4%'                    # 语速
VOLUME = '+0%'                  # 音量
OUTPUT_FILE = "test.mp3"        # 输出音频文件名

def read_text_from_file(filename: str) -> str:
    """
    从指定文件读取文本内容
    :param filename: 文件名
    :return: 文件中的文本内容
    """
    with open(filename, 'r', encoding='utf-8') as f:
        return f.read()

async def amain(text: str) -> None:
    """
    调用 edge_tts 进行语音合成并保存为音频文件
    :param text: 需要合成的文本内容
    """
    communicate = edge_tts.Communicate(text, VOICE, rate=RATE, volume=VOLUME)
    with open(OUTPUT_FILE, "wb") as file:
        async for chunk in communicate.stream():
            if chunk["type"] == "audio":
                file.write(chunk["data"])
            elif chunk["type"] == "WordBoundary":
                print(f"WordBoundary: {chunk}")  # 打印单词边界信息（可选）

if __name__ == "__main__":
    # 读取文本内容
    text = read_text_from_file('text2voicetest.txt')
    print(f"待合成文本：{text}")  # 打印读取到的文本
    # 执行语音合成
    asyncio.run(amain(text))
